<template>
  <view class="chat-page">
    <!-- 顶部用户信息 -->
    <view class="chat-header">
      <view class="user-info">
        <view class="avatar" :style="avatarStyle">{{ username.slice(0,1) }}</view>
        <text class="username">{{ username }}</text>
      </view>
    </view>
    
    <!-- 聊天记录区域 -->
    <scroll-view 
      class="chat-messages" 
      :scroll-y="true"
      :scroll-with-animation="true"
      :scroll-top="scrollTop"
      @tap="handleScrollViewTap"
    >
      <view class="messages-container">
        <view 
          v-for="(message, index) in messages" 
          :key="index" 
          :class="['message', message.sender === 'me' ? 'my-message' : 'other-message']"
        >
          <!-- 对方消息 -->
          <view v-if="message.sender !== 'me'" class="other-message-content">
            <view class="avatar" :style="avatarStyle">{{ username.slice(0,1) }}</view>
            <view class="message-bubble">
              <text class="message-text">{{ message.content }}</text>
            </view>
          </view>
          
          <!-- 我的消息 -->
          <view v-else class="my-message-content">
            <view class="message-bubble">
              <text class="message-text">{{ message.content }}</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 底部输入区域作为一个独立模块 -->
    <view class="input-module">
      <view class="chat-input-container" :style="{ paddingBottom: safeAreaBottom + 'px' }">
        <input 
          ref="messageInput"
          class="chat-input" 
          v-model="inputMessage" 
          placeholder="输入消息..." 
          @confirm="sendMessage"
          :focus="inputFocus"
          @blur="onInputBlur"
          @focus="onInputFocus"
          confirm-type="send"
        />
        <view class="send-button" @click="sendMessage" @touchstart="onSendButtonPress">
          <image class="send-icon" src="/static/icon/send.png" mode="aspectFit"></image>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      inputMessage: '',
      scrollTop: 0,
      inputFocus: false,
      safeAreaBottom: 0,
      keyboardHeight: 0,
      messages: [
        { sender: 'other', content: '你好！' },
        { sender: 'me', content: '你好，有什么可以帮助你的吗？' },
        { sender: 'other', content: '我想了解一下之前提到的那个任务' },
        { sender: 'me', content: '好的，请问是哪个任务呢？' }
      ],
      // 添加标志位来控制焦点行为
      isSending: false,
      shouldFocusInput: false,
      // 添加定时器引用
      focusTimer: null
    }
  },
  
  computed: {
    avatarStyle() {
      const colors = [
        'linear-gradient(135deg,#6dd5ed 0%,#2193b0 100%)',
        'linear-gradient(135deg,#f6d365 0%,#fda085 100%)',
        'linear-gradient(135deg,#a1c4fd 0%,#c2e9fb 100%)',
        'linear-gradient(135deg,#d4fc79 0%,#96e6a1 100%)'
      ]
      const index = this.username.charCodeAt(0) % colors.length
      return {
        background: colors[index],
        color: '#fff'
      }
    }
  },
  
  onLoad(options) {
    if (options.username) {
      this.username = decodeURIComponent(options.username)
      uni.setNavigationBarTitle({
        title: this.username
      })
    }
    
    // 获取安全区域
    this.getSafeArea()
    
    // 监听键盘高度变化
    this.listenKeyboard()
  },
  
  onUnload() {
    // 页面卸载时取消键盘高度监听
    uni.offKeyboardHeightChange()
    // 清理定时器
    if (this.focusTimer) {
      clearTimeout(this.focusTimer)
      this.focusTimer = null
    }
  },
  
  methods: {
    // 获取安全区域
    getSafeArea() {
      const systemInfo = uni.getSystemInfoSync()
      this.safeAreaBottom = systemInfo.safeAreaInsets?.bottom || 0
    },
    
    // 监听键盘
    listenKeyboard() {
      uni.onKeyboardHeightChange(res => {
        this.keyboardHeight = res.height
        if (res.height > 0) {
          // 键盘弹出时，滚动到底部
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        }
      })
    },
    
    // 输入框失去焦点
    onInputBlur() {
      // 只有在非发送状态下才真正失去焦点
      if (!this.isSending) {
        this.inputFocus = false
      }
    },
    
    // 输入框获得焦点
    onInputFocus() {
      this.inputFocus = true
    },
    
    // 发送按钮按下事件
    onSendButtonPress() {
      // 确保在点击发送按钮时保持输入框焦点
      this.inputFocus = true
    },
    
    // 点击聊天区域处理
    handleScrollViewTap() {
      // 点击聊天区域时，如果当前没有焦点，则设置焦点
      if (!this.inputFocus) {
        this.inputFocus = true
      }
    },
    
    sendMessage() {
      if (this.inputMessage.trim() === '') return
      
      // 设置发送状态，防止焦点丢失
      this.isSending = true
      
      // 添加消息到列表
      this.messages.push({
        sender: 'me',
        content: this.inputMessage
      })
      
      // 清空输入框
      const messageToSend = this.inputMessage
      this.inputMessage = ''
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
        
        // 使用更可靠的延迟来保持输入框焦点
        if (this.focusTimer) {
          clearTimeout(this.focusTimer)
        }
        
        this.focusTimer = setTimeout(() => {
          this.isSending = false
          // 确保输入框重新获得焦点
          this.inputFocus = true
          this.focusTimer = null
        }, 100)
      })
    },
    
    // 滚动到底部
    scrollToBottom() {
      // 使用nextTick确保DOM更新完成
      this.$nextTick(() => {
        setTimeout(() => {
          // 创建一个选择器查询，获取scroll-view的高度和内容高度
          const query = uni.createSelectorQuery().in(this)
          query.select('.chat-messages').boundingClientRect()
          query.select('.messages-container').boundingClientRect()
          query.exec((res) => {
            if (res[0] && res[1]) {
              const scrollViewHeight = res[0].height
              const contentHeight = res[1].height
              // 计算滚动位置，确保显示最新消息
              this.scrollTop = contentHeight + 100
            }
          })
        }, 50)
      })
    }
  }
}
</script>

<style scoped>
/* 修复背景颜色问题 - 设置页面根元素背景 */
page {
  background: linear-gradient(180deg, #eef2ff 0%, #f8fafc 100%);
  height: 100%;
}

.chat-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: linear-gradient(180deg, #eef2ff 0%, #f8fafc 100%);
  box-sizing: border-box;
  position: relative;
}

/* 确保背景覆盖整个区域 */
.chat-page::before {
  content: '';
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(180deg, #eef2ff 0%, #f8fafc 100%);
  z-index: -1;
}

/* 顶部用户信息 */
.chat-header {
  padding: 12px;
  background: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  z-index: 10;
  position: relative;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-weight: 700;
  font-size: 16px;
}

.username {
  font-size: 18px;
  font-weight: 700;
  color: #16202b;
}

/* 聊天记录区域 - 修复背景 */
.chat-messages {
  flex: 1;
  padding: 16px 12px;
  box-sizing: border-box;
  background: transparent; /* 设置为透明，显示父级背景 */
  min-height: 0; /* 允许flex收缩 */
}

.messages-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-height: 100%; /* 确保容器至少充满整个区域 */
}

.message {
  display: flex;
  flex-direction: column;
}

/* 对方消息 */
.other-message-content {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.other-message .message-bubble {
  background: #ffffff;
  border-radius: 18px 18px 18px 4px;
  padding: 12px 16px;
  max-width: 70%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  word-break: break-word;
}

/* 我的消息 */
.my-message {
  align-items: flex-end;
}

.my-message-content {
  display: flex;
  justify-content: flex-end;
}

.my-message .message-bubble {
  background: #56BAEC;
  color: white;
  border-radius: 18px 18px 4px 18px;
  padding: 12px 16px;
  max-width: 70%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  word-break: break-word;
}

.message-text {
  font-size: 16px;
  line-height: 1.4;
}

/* 将输入框模块固定在底部 */
.input-module {
  position: sticky;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
}

/* 底部输入区域 */
.chat-input-container {
  display: flex;
  align-items: center;
  padding: 12px;
  background: #ffffff;
  border-top: 1px solid #eee;
  gap: 10px;
  position: relative;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
}

.chat-input {
  flex: 1;
  padding: 12px 16px;
  background: #f5f7fa;
  border-radius: 24px;
  border: none;
  outline: none;
  font-size: 16px;
}

.send-button {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #56BAEC;
  cursor: pointer;
}

.send-icon {
  width: 20px;
  height: 20px;
}

/* 聊天记录区域 */
.chat-messages {
  flex: 1;
  padding: 16px 12px;
  box-sizing: border-box;
  background: transparent;
  min-height: 0;
}
</style>